<template>
    <div>
        <el-tree
            default-expand-all
            ref="menuTreeRef"
            :data="menuTree"
            node-key="id"
            show-checkbox
            :props="defaultProps"
            :expand-on-click-node="true"
        ></el-tree>

        <el-button style="margin-top: 20px" @click="onAuthorConfirm"
            >确定</el-button
        >
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { api } from '@/api/index'
const { RequestAuthorRole, RequestAuthResource, RequestReourceAll } = api
let menuTree = ref([])
let selectMenuTree = ref([])
const menuTreeRef = ref(null)
const defaultProps = {
    children: 'children',
    label: 'label',
}

const props = defineProps({
    currentRoleId: Number,
})
onMounted(() => {
    getMenuList()
})
/**
 * 获取菜单数据
 */
const getMenuList = () => {
    RequestReourceAll().then(data => {
        let { resultCode, resultInfo } = data
        if (resultCode === 1) {
            menuTree.value = resultInfo
            // 先设置显示node，再设置选中node
            getMenuListByRole(props.currentRoleId)
        }
    })
}
/**
 * 当前菜单数据
 */
const getMenuListByRole = roleId => {
    RequestAuthResource(roleId).then(data => {
        let { resultCode, resultInfo } = data
        if (resultCode === 1) {
            selectMenuTree.value = resultInfo
            menuTreeRef.value.setCheckedNodes(resultInfo)
        }
    })
}

/**
 * 设置权限
 */
const onAuthorConfirm = () => {
    let selectTree = menuTreeRef.value.getCheckedNodes()
    let arr = selectTree.map(item => item.id)
    let ids = arr.join(',')
    console.log(ids)
    console.log(props.currentRoleId)

    const resType = 2 //2 按钮级资源权限，0 菜单权限
    RequestAuthorRole(props.currentRoleId, ids, resType).then(data => {
        if (data.resultCode === 1) {
            ElMessage.success('设置成功!')
        }
    })
}
</script>

<style lang="scss" scoped></style>
